package com.example.xiancheng_handler;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class MainActivity extends AppCompatActivity {
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();

    }
    private void init()
    {
        Button button = findViewById(R.id.but_faxiaoxi);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击向主线程发送消息
                sendMsg();
            }
        });

        //创建主线程Handler
        //Handler构造方法中通过Looper的静态方法，传输Looper
        //即使谁的Handler
        //Looper.getMainLooper()  获取主线程Looper
        //Looper.mylooper()获取当前线程Looper，如果当前线程没有Looper
        //则为其创建型的Looper
        //故，
        handler = new Handler(Looper.getMainLooper())
        {
            //消息处理方法
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                //通过Message.what字段，区分不同来源的消息
                switch (msg.what)
                {
                    case 1:
                    String str1 = (String) msg.obj;
                        Toast.makeText(MainActivity.this, "主线程收到" + str1, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
    }
    private void sendMsg()
    {
        new Thread()
        {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i < 5; i++) {
                    //发送消息方法1
                    //创建消息
                    Message message = new Message();
                    //消息标识，用于区分那个子线程发送的消息
                    message.what = 1;
                    //附带数据
                    message.obj = "来自子线程" + i +"的数据";
                    try {
                        sleep(2500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //立即发送消息
                    handler.sendMessage(message);
                    //发送消息方法2
                    //获取Messagequeue众先知的消息
//                    Message message1 = handler.obtainMessage();
//                    message1.what = 2;
//                    message1.obj = "来自子线程2的消息";
//
//                    //发送消息至此
//                    message1.sendToTarget();
                }
            }
        }.start();
    }

}